package cate.game.res;

import cate.common.util.GameResult;
import cate.game.role.Role;

import java.util.function.Function;


public class MixResConsumer<R> {
    private MixRes consume;
    private boolean tips = true;
    private Function<Role, R> function;
    private int operation;
    private int operationSub;
    private String msg;

    public MixResConsumer<R> res(MixRes consume) {
        this.consume = consume;
        return this;
    }

    public MixResConsumer<R> tips(boolean tips) {
        this.tips = tips;
        return this;
    }

    public MixResConsumer<R> success(Function<Role, R> function) {
        this.function = function;
        return this;
    }

    public MixResConsumer<R> msg(String msg) {
        this.msg = msg;
        return this;
    }

    public MixResConsumer<R> operation(int operation, int operationSub) {
        this.operation = operation;
        this.operationSub = operationSub;
        return this;
    }

    public GameResult<R> exe(Role role) {
        GameResult<R> r = new GameResult<>();
        if (consume != null) {
            boolean existOp = operation > 0 || operationSub > 0;
            if (existOp) {
                role.log.setOperation(operation);
                role.log.setOperationSub(operationSub);
            }
            GameResult<MixResItem> consumeRes = consume.consume(role, null);
            if (!consumeRes.ok()) {
                if (tips) {
                    role.getGame().notice.tipResItem(role, consumeRes.data);
                }
                return r.fail(consumeRes);
            }
            if (function != null) {
                r.data = function.apply(role);
            }
            if (existOp) {
                role.log.clearOperation();
            }
        }
        if (msg != null) {
            r.message = msg;
        }
        return r;
    }
}
